"""
API服务适配器
API Service Adapters
简化的服务层，为API端点提供直接的数据访问方法
"""
import logging
import asyncio
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
import json

from database.simple_db import get_database_manager

logger = logging.getLogger(__name__)


class CameraService:
    """摄像头服务适配器"""
    
    def __init__(self):
        self.db = get_database_manager()
    
    async def get_cameras(self, status: Optional[str] = None, ai_enabled: Optional[bool] = None, limit: int = 100) -> List[Dict[str, Any]]:
        """获取摄像头列表"""
        try:
            filters = {}
            if status:
                filters['status'] = status
            if ai_enabled is not None:
                filters['ai_enabled'] = ai_enabled
            
            cameras, total = self.db.get_camera_list(filters=filters, size=limit)
            
            # 处理ai_algorithms字段
            for camera in cameras:
                if camera.get('ai_algorithms'):
                    try:
                        camera['ai_services'] = json.loads(camera['ai_algorithms'])
                    except:
                        camera['ai_services'] = []
                else:
                    camera['ai_services'] = []
            
            return cameras
        except Exception as e:
            logger.error(f"获取摄像头列表失败: {e}")
            raise
    
    async def get_camera(self, camera_id: str) -> Optional[Dict[str, Any]]:
        """获取单个摄像头"""
        try:
            camera = None
            
            # 尝试按ID获取（如果是数字）
            try:
                camera_id_int = int(camera_id)
                camera = self.db.get_camera_by_id(camera_id_int)
            except ValueError:
                # 如果不是数字，按名称获取
                camera = self.db.get_camera_by_name(camera_id)
            
            if camera:
                # 处理ai_algorithms字段
                if camera.get('ai_algorithms'):
                    try:
                        camera['ai_services'] = json.loads(camera['ai_algorithms'])
                    except:
                        camera['ai_services'] = []
                else:
                    camera['ai_services'] = []
                
                return camera
            
            return None
        except Exception as e:
            logger.error(f"获取摄像头失败: {e}")
            return None
    
    async def get_camera_by_name(self, name: str) -> Optional[Dict[str, Any]]:
        """按名称获取摄像头"""
        try:
            return self.db.get_camera_by_name(name)
        except Exception as e:
            logger.error(f"按名称获取摄像头失败: {e}")
            return None
    
    async def get_camera_by_camera_id(self, camera_id: str) -> Optional[Dict[str, Any]]:
        """按camera_id获取摄像头"""
        try:
            # 在简化版本中，camera_id通常映射到name字段
            return self.db.get_camera_by_name(camera_id)
        except Exception as e:
            logger.error(f"按camera_id获取摄像头失败: {e}")
            return None
    
    async def create_camera(self, camera_data: Dict[str, Any]) -> Optional[int]:
        """创建摄像头"""
        try:
            # 处理ai_services字段
            if 'ai_services' in camera_data and isinstance(camera_data['ai_services'], list):
                camera_data['ai_algorithms'] = json.dumps(camera_data['ai_services'])
                del camera_data['ai_services']
            
            # 如果有camera_id字段但没有name，使用camera_id作为name
            if 'camera_id' in camera_data and not camera_data.get('name'):
                camera_data['name'] = camera_data['camera_id']
            
            # 确保name字段存在
            if not camera_data.get('name'):
                camera_data['name'] = f"Camera_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            
            # 设置默认状态
            if 'status' not in camera_data:
                camera_data['status'] = 'created'
            
            # 处理stream_url字段映射到rtsp_url
            if 'stream_url' in camera_data:
                camera_data['rtsp_url'] = camera_data['stream_url']
                del camera_data['stream_url']
            
            # 处理device_id和channel_id字段映射到WVP字段
            if 'device_id' in camera_data:
                camera_data['wvp_device_id'] = camera_data['device_id']
                del camera_data['device_id']
            
            if 'channel_id' in camera_data:
                camera_data['wvp_channel_id'] = camera_data['channel_id']
                del camera_data['channel_id']
            
            # 设置默认值
            camera_data.setdefault('longitude', 0.0)
            camera_data.setdefault('latitude', 0.0)
            camera_data.setdefault('ai_enabled', camera_data.get('ai_enabled', True))
            
            # 移除camera_id字段，因为数据库表中没有这个字段
            if 'camera_id' in camera_data:
                del camera_data['camera_id']
            
            # 移除不需要的字段
            for field in ['resolution', 'fps']:
                if field in camera_data:
                    del camera_data[field]
            
            camera_id = self.db.create_camera(camera_data)
            return camera_id
        except Exception as e:
            logger.error(f"创建摄像头失败: {e}")
            raise
    
    async def update_camera(self, camera_id: str, update_data: Dict[str, Any]) -> bool:
        """更新摄像头"""
        try:
            # 处理ai_services字段
            if 'ai_services' in update_data and isinstance(update_data['ai_services'], list):
                update_data['ai_algorithms'] = json.dumps(update_data['ai_services'])
                del update_data['ai_services']
            
            # 尝试按ID更新
            try:
                camera_id_int = int(camera_id)
                return self.db.update_camera(camera_id_int, update_data)
            except ValueError:
                # 如果不是数字，需要先找到ID
                camera = self.db.get_camera_by_name(camera_id)
                if camera:
                    return self.db.update_camera(camera['id'], update_data)
                return False
        except Exception as e:
            logger.error(f"更新摄像头失败: {e}")
            raise
    
    async def delete_camera(self, camera_id: str) -> bool:
        """删除摄像头"""
        try:
            # 尝试按ID删除
            try:
                camera_id_int = int(camera_id)
                return self.db.delete_camera(camera_id_int)
            except ValueError:
                # 如果不是数字，需要先找到ID
                camera = self.db.get_camera_by_name(camera_id)
                if camera:
                    return self.db.delete_camera(camera['id'])
                return False
        except Exception as e:
            logger.error(f"删除摄像头失败: {e}")
            raise
    
    async def enable_ai_services(self, camera_id: str, services: List[str]) -> bool:
        """启用AI服务"""
        try:
            update_data = {
                'ai_enabled': True,
                'ai_algorithms': json.dumps(services)
            }
            
            # 尝试按ID更新
            try:
                camera_id_int = int(camera_id)
                return self.db.update_camera(camera_id_int, update_data)
            except ValueError:
                # 如果不是数字，需要先找到ID
                camera = self.db.get_camera_by_name(camera_id)
                if camera:
                    return self.db.update_camera(camera['id'], update_data)
                return False
        except Exception as e:
            logger.error(f"启用AI服务失败: {e}")
            raise
    
    async def disable_ai_services(self, camera_id: str) -> bool:
        """禁用AI服务"""
        try:
            update_data = {
                'ai_enabled': False,
                'ai_algorithms': json.dumps([])
            }
            
            # 尝试按ID更新
            try:
                camera_id_int = int(camera_id)
                return self.db.update_camera(camera_id_int, update_data)
            except ValueError:
                # 如果不是数字，需要先找到ID
                camera = self.db.get_camera_by_name(camera_id)
                if camera:
                    return self.db.update_camera(camera['id'], update_data)
                return False
        except Exception as e:
            logger.error(f"禁用AI服务失败: {e}")
            raise
    
    async def get_camera_status(self, camera_id: str) -> Optional[Dict[str, Any]]:
        """获取摄像头状态"""
        try:
            camera = await self.get_camera(camera_id)
            if not camera:
                return None
            
            return {
                'camera_id': camera_id,
                'status': camera.get('status'),
                'ai_enabled': camera.get('ai_enabled'),
                'ai_services': camera.get('ai_services', []),
                'last_updated': camera.get('updated_at')
            }
        except Exception as e:
            logger.error(f"获取摄像头状态失败: {e}")
            raise


class WVPDeviceService:
    """WVP设备服务适配器 - 从Java后端获取数据"""
    
    def __init__(self):
        self.db = get_database_manager()
        # 尝试多个可能的WVP服务地址
        self.wvp_urls = [
            "http://localhost:18080",  # 默认WVP端口
            "http://localhost:8080",   # 备用端口
            "http://127.0.0.1:18080",
            "http://127.0.0.1:8080"
        ]
        self.wvp_username = "admin"
        self.wvp_password = "admin123"
    
    async def get_devices(self, status: Optional[str] = None, online: Optional[bool] = None, limit: int = 100) -> List[Dict[str, Any]]:
        """获取WVP设备列表 - 优先从Java后端获取"""
        # 首先尝试从Java后端获取实时数据
        try:
            from sync_real_wvp_data import RealWVPClient
            
            # 尝试连接不同的WVP服务地址
            for wvp_url in self.wvp_urls:
                try:
                    async with RealWVPClient(wvp_url) as client:
                        if await client.test_connection():
                            devices = await client.get_devices()
                            if devices:
                                # 转换为统一格式
                                result = []
                                for device in devices:
                                    device_info = {
                                        "device_id": device.get("deviceId") or device.get("id") or device.get("device_id"),
                                        "device_name": (device.get("name") or 
                                                      device.get("deviceName") or 
                                                      device.get("device_name") or 
                                                      f"设备-{device.get('deviceId', device.get('id'))}"),
                                        "manufacturer": device.get("manufacturer", ""),
                                        "model": device.get("model", ""),
                                        "ip": device.get("ip") or device.get("hostAddress", ""),
                                        "port": device.get("port", 5060),
                                        "status": "online" if device.get("online", False) else "offline",
                                        "register_time": device.get("registerTime", ""),
                                        "keepalive_time": device.get("keepaliveTime", ""),
                                        "channel_count": device.get("channelCount", 0)
                                    }
                                    
                                    # 应用过滤条件
                                    if status and device_info["status"] != status:
                                        continue
                                    if online is not None:
                                        device_online = device_info["status"] == "online"
                                        if online != device_online:
                                            continue
                                    
                                    result.append(device_info)
                                
                                logger.info(f"从Java后端 {wvp_url} 获取到 {len(result)} 个WVP设备")
                                return result[:limit]
                except Exception as e:
                    logger.debug(f"尝试连接 {wvp_url} 失败: {e}")
                    continue
            
            logger.warning("无法连接到Java后端WVP服务，使用本地数据")
                
        except Exception as e:
            logger.error(f"从Java后端获取WVP设备列表失败: {e}")
        
        # 降级到本地数据库
        try:
            query = "SELECT * FROM wvp_devices WHERE 1=1"
            params = []
            
            if status:
                query += " AND status = ?"
                params.append(status)
            if online is not None:
                query += " AND status = ?"
                params.append('online' if online else 'offline')
            
            query += " ORDER BY created_at DESC LIMIT ?"
            params.append(limit)
            
            local_devices = self.db.execute_query(query, tuple(params))
            logger.info(f"从本地数据库获取到 {len(local_devices)} 个WVP设备")
            return local_devices
        except Exception as db_e:
            logger.error(f"从本地数据库获取WVP设备也失败: {db_e}")
            return []
    
    async def get_device(self, device_id: str) -> Optional[Dict[str, Any]]:
        """获取单个WVP设备"""
        try:
            query = "SELECT * FROM wvp_devices WHERE device_id = ?"
            results = self.db.execute_query(query, (device_id,))
            return results[0] if results else None
        except Exception as e:
            logger.error(f"获取WVP设备失败: {e}")
            return None
    
    async def register_device(self, device_data: Dict[str, Any]) -> Optional[str]:
        """注册WVP设备"""
        try:
            # 检查设备是否已存在
            existing_device = await self.get_device(device_data.get('device_id'))
            if existing_device:
                # 更新现有设备
                query = """
                    UPDATE wvp_devices SET 
                        device_name = ?, manufacturer = ?, model = ?, ip = ?, port = ?,
                        status = 'online', register_time = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
                    WHERE device_id = ?
                """
                params = (
                    device_data.get('device_name'),
                    device_data.get('manufacturer'),
                    device_data.get('model'),
                    device_data.get('ip_address'),
                    device_data.get('port', 5060),
                    device_data.get('device_id')
                )
                self.db.execute_update(query, params)
            else:
                # 插入新设备
                query = """
                    INSERT INTO wvp_devices (
                        device_id, device_name, manufacturer, model, ip, port,
                        status, register_time, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, 'online', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
                """
                params = (
                    device_data.get('device_id'),
                    device_data.get('device_name'),
                    device_data.get('manufacturer'),
                    device_data.get('model'),
                    device_data.get('ip_address'),
                    device_data.get('port', 5060)
                )
                self.db.execute_insert(query, params)
            
            # 为设备创建默认通道
            await self._create_default_channels(device_data.get('device_id'))
            
            return device_data.get('device_id')
        except Exception as e:
            logger.error(f"注册WVP设备失败: {e}")
            raise
    
    async def _create_default_channels(self, device_id: str):
        """为设备创建默认通道"""
        try:
            # 检查是否已有通道
            existing_channels = await WVPChannelService().get_device_channels(device_id)
            if existing_channels:
                return
            
            # 创建默认通道
            query = """
                INSERT INTO wvp_channels (
                    device_id, channel_id, channel_name, status, created_at
                ) VALUES (?, ?, ?, 'online', CURRENT_TIMESTAMP)
            """
            params = (device_id, device_id, f"通道-{device_id}")
            self.db.execute_insert(query, params)
            
        except Exception as e:
            logger.error(f"创建默认通道失败: {e}")
    
    async def unregister_device(self, device_id: str) -> bool:
        """注销WVP设备"""
        try:
            query = "DELETE FROM wvp_devices WHERE device_id = ?"
            affected = self.db.execute_update(query, (device_id,))
            return affected > 0
        except Exception as e:
            logger.error(f"注销WVP设备失败: {e}")
            return False
    
    async def update_keepalive(self, device_id: str) -> bool:
        """更新设备保活时间"""
        try:
            query = """
                UPDATE wvp_devices 
                SET keepalive_time = CURRENT_TIMESTAMP, status = 'online', updated_at = CURRENT_TIMESTAMP
                WHERE device_id = ?
            """
            affected = self.db.execute_update(query, (device_id,))
            return affected > 0
        except Exception as e:
            logger.error(f"更新设备保活失败: {e}")
            return False
    
    async def get_device_status(self, device_id: str) -> Optional[Dict[str, Any]]:
        """获取设备状态"""
        try:
            device = await self.get_device(device_id)
            if not device:
                return None
            
            return {
                'device_id': device_id,
                'status': device.get('status'),
                'online': device.get('status') == 'online',
                'last_keepalive': device.get('keepalive_time'),
                'channel_count': device.get('channel_count', 0)
            }
        except Exception as e:
            logger.error(f"获取设备状态失败: {e}")
            return None


class WVPChannelService:
    """WVP通道服务适配器"""
    
    def __init__(self):
        self.db = get_database_manager()
        # 使用与WVPDeviceService相同的配置
        self.wvp_urls = [
            "http://localhost:18080",
            "http://localhost:8080",
            "http://127.0.0.1:18080",
            "http://127.0.0.1:8080"
        ]
    
    async def get_device_channels(self, device_id: str) -> List[Dict[str, Any]]:
        """获取设备通道列表 - 优先从Java后端获取"""
        # 首先尝试从Java后端获取实时数据
        try:
            from sync_real_wvp_data import RealWVPClient
            
            # 尝试连接不同的WVP服务地址
            for wvp_url in self.wvp_urls:
                try:
                    async with RealWVPClient(wvp_url) as client:
                        if await client.test_connection():
                            channels = await client.get_device_channels(device_id)
                            if channels:
                                # 转换为统一格式
                                result = []
                                for channel in channels:
                                    channel_info = {
                                        "device_id": device_id,
                                        "channel_id": (channel.get("channelId") or 
                                                     channel.get("id") or 
                                                     channel.get("channel_id") or 
                                                     device_id),
                                        "channel_name": (channel.get("name") or 
                                                       channel.get("channelName") or 
                                                       channel.get("channel_name") or 
                                                       f"通道-{channel.get('channelId', device_id)}"),
                                        "status": "online" if channel.get("status") == "ON" else "offline",
                                        "longitude": channel.get("longitude"),
                                        "latitude": channel.get("latitude"),
                                        "address": channel.get("address", ""),
                                        "channel_type": channel.get("channelType", 0),
                                        "sub_count": channel.get("subCount", 0),
                                        "has_audio": channel.get("hasAudio", False),
                                        "ptz_type": channel.get("ptzType", 0)
                                    }
                                    result.append(channel_info)
                                
                                logger.info(f"从Java后端 {wvp_url} 获取到设备 {device_id} 的 {len(result)} 个通道")
                                return result
                except Exception as e:
                    logger.debug(f"尝试从 {wvp_url} 获取设备 {device_id} 通道失败: {e}")
                    continue
            
            logger.warning(f"无法从Java后端获取设备 {device_id} 的通道，使用本地数据")
                
        except Exception as e:
            logger.error(f"从Java后端获取设备通道列表失败: {e}")
        
        # 降级到本地数据库
        try:
            query = "SELECT * FROM wvp_channels WHERE device_id = ? ORDER BY created_at DESC"
            local_channels = self.db.execute_query(query, (device_id,))
            logger.info(f"从本地数据库获取到设备 {device_id} 的 {len(local_channels)} 个通道")
            return local_channels
        except Exception as db_e:
            logger.error(f"从本地数据库获取设备通道也失败: {db_e}")
            return []
    
    async def get_play_url(self, channel_id: str) -> Optional[Dict[str, Any]]:
        """获取通道播放地址"""
        try:
            # 这里应该调用WVP服务获取实际播放地址
            # 现在返回模拟数据
            return {
                'channel_id': channel_id,
                'play_url': f'rtmp://localhost:1935/live/{channel_id}',
                'hls_url': f'http://localhost:8080/hls/{channel_id}.m3u8',
                'status': 'active'
            }
        except Exception as e:
            logger.error(f"获取播放地址失败: {e}")
            return None


class AIAnalysisService:
    """AI分析服务适配器"""
    
    def __init__(self):
        self.db = get_database_manager()
    
    async def get_available_services(self) -> List[Dict[str, Any]]:
        """获取可用的AI服务列表"""
        return [
            {
                'service_id': 'behavior_monitoring',
                'service_name': '行为监控',
                'description': '检测异常行为和活动',
                'status': 'active'
            },
            {
                'service_id': 'crowd_safety',
                'service_name': '人群安全',
                'description': '人群密度和安全监测',
                'status': 'active'
            },
            {
                'service_id': 'energy_management',
                'service_name': '能源管理',
                'description': '能源使用分析和优化',
                'status': 'active'
            },
            {
                'service_id': 'environment_hygiene',
                'service_name': '环境卫生',
                'description': '环境质量监测',
                'status': 'active'
            },
            {
                'service_id': 'classroom_quality',
                'service_name': '课堂质量',
                'description': '智能课堂质量评估',
                'status': 'active'
            },
            {
                'service_id': 'teaching_quality',
                'service_name': '教学质量',
                'description': '教学质量评估',
                'status': 'active'
            }
        ]
    
    async def save_analysis_result(self, result_data: Dict[str, Any]) -> Optional[int]:
        """保存AI分析结果"""
        try:
            camera_id = result_data.get('camera_id')
            algorithm = result_data.get('algorithm', 'unknown')
            result_json = json.dumps(result_data.get('result_data', {}))
            confidence = result_data.get('confidence', 0.0)
            processing_time = result_data.get('processing_time', 0.0)
            
            return self.db.save_ai_result(camera_id, algorithm, result_json, confidence, processing_time)
        except Exception as e:
            logger.error(f"保存AI分析结果失败: {e}")
            raise
    
    async def get_analysis_results(self, camera_id: str, algorithm: Optional[str] = None, 
                                 limit: int = 100) -> List[Dict[str, Any]]:
        """获取AI分析结果"""
        try:
            camera_id_int = int(camera_id)
            results = self.db.get_ai_results(camera_id_int, algorithm, limit)
            
            # 处理result_data字段
            for result in results:
                if result.get('result_data'):
                    try:
                        result['result_data'] = json.loads(result['result_data'])
                    except:
                        pass
            
            return results
        except Exception as e:
            logger.error(f"获取AI分析结果失败: {e}")
            return []
    
    async def get_latest_result(self, camera_id: str, algorithm: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """获取最新的AI分析结果"""
        try:
            results = await self.get_analysis_results(camera_id, algorithm, 1)
            return results[0] if results else None
        except Exception as e:
            logger.error(f"获取最新AI分析结果失败: {e}")
            return None
    
    async def get_analysis_statistics(self, camera_id: str, algorithm: Optional[str] = None) -> Dict[str, Any]:
        """获取AI分析统计信息"""
        try:
            camera_id_int = int(camera_id)
            results = self.db.get_ai_results(camera_id_int, algorithm, 1000)
            
            if not results:
                return {
                    'total_count': 0,
                    'avg_confidence': 0.0,
                    'latest_analysis': None
                }
            
            total_count = len(results)
            avg_confidence = sum(r.get('confidence', 0) for r in results) / total_count
            latest_analysis = results[0].get('created_at') if results else None
            
            return {
                'total_count': total_count,
                'avg_confidence': avg_confidence,
                'latest_analysis': latest_analysis
            }
        except Exception as e:
            logger.error(f"获取AI分析统计失败: {e}")
            return {}
    
    async def delete_results(self, camera_id: str) -> bool:
        """删除AI分析结果"""
        try:
            camera_id_int = int(camera_id)
            # 使用数据库的清理方法
            affected = self.db.cleanup_old_ai_results(0)  # 删除所有结果
            return affected > 0
        except Exception as e:
            logger.error(f"删除AI分析结果失败: {e}")
            return False


class VideoStreamService:
    """视频流服务适配器"""
    
    def __init__(self):
        self.db = get_database_manager()
    
    async def get_stream_info(self, camera_id: str) -> Optional[Dict[str, Any]]:
        """获取视频流信息"""
        try:
            camera = await CameraService().get_camera(camera_id)
            if not camera:
                return None
            
            return {
                'camera_id': camera_id,
                'stream_url': camera.get('rtsp_url'),
                'status': camera.get('stream_status', 'inactive'),
                'resolution': camera.get('resolution', '1920x1080'),
                'fps': camera.get('processing_fps', 25)
            }
        except Exception as e:
            logger.error(f"获取视频流信息失败: {e}")
            return None
    
    async def get_video_stream(self, camera_id: str, format: str = "flv", quality: str = "high"):
        """获取视频流生成器"""
        try:
            # 检查摄像头是否存在
            camera_service = CameraService()
            camera = await camera_service.get_camera(camera_id)
            if not camera:
                logger.error(f"摄像头不存在: {camera_id}")
                return None
            
            # 模拟视频流数据
            async def stream_generator():
                for i in range(100):
                    yield f"video_frame_{i}_camera_{camera_id}\n".encode()
                    await asyncio.sleep(0.1)
            
            return stream_generator()
        except Exception as e:
            logger.error(f"获取视频流失败: {e}")
            return None
    
    async def start_stream(self, camera_id: str) -> bool:
        """启动视频流"""
        try:
            # 模拟启动视频流
            return True
        except Exception as e:
            logger.error(f"启动视频流失败: {e}")
            return False
    
    async def stop_stream(self, camera_id: str) -> bool:
        """停止视频流"""
        try:
            # 模拟停止视频流
            return True
        except Exception as e:
            logger.error(f"停止视频流失败: {e}")
            return False
    
    async def get_snapshot(self, camera_id: str) -> Optional[bytes]:
        """获取视频快照"""
        try:
            # 返回模拟快照数据
            return b"fake_jpeg_data_for_camera_" + camera_id.encode()
        except Exception as e:
            logger.error(f"获取快照失败: {e}")
            return None
    
    async def start_recording(self, camera_id: str, duration: int = 3600) -> Optional[str]:
        """开始录制"""
        try:
            record_id = f"{camera_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            return record_id
        except Exception as e:
            logger.error(f"开始录制失败: {e}")
            return None
    
    async def stop_recording(self, camera_id: str) -> Optional[Dict[str, Any]]:
        """停止录制"""
        try:
            return {
                'record_id': f"{camera_id}_recording",
                'duration': 1800,
                'file_size': 512000,
                'status': 'completed'
            }
        except Exception as e:
            logger.error(f"停止录制失败: {e}")
            return None
    
    async def get_recordings(self, camera_id: str, limit: int = 50, days: int = 7) -> List[Dict[str, Any]]:
        """获取录制列表"""
        try:
            # 返回模拟录制数据
            return [
                {
                    'record_id': f'{camera_id}_001',
                    'camera_id': camera_id,
                    'start_time': '2025-09-04T10:00:00Z',
                    'end_time': '2025-09-04T11:00:00Z',
                    'duration': 3600,
                    'file_size': 1024000,
                    'status': 'completed'
                }
            ]
        except Exception as e:
            logger.error(f"获取录制列表失败: {e}")
            return []
    
    async def get_playback_stream(self, record_id: str):
        """获取回放流"""
        try:
            # 模拟回放流
            async def playback_generator():
                for i in range(50):
                    yield f"playback_frame_{i}_record_{record_id}\n".encode()
                    await asyncio.sleep(0.1)
            
            return playback_generator()
        except Exception as e:
            logger.error(f"获取回放流失败: {e}")
            return None